#include "HashMap.h"


HashMap::HashMap(int size):size(size)
{
    array=new Node*[size];
    for (int i = 0; i <size; i++)
    {
        array[i]=nullptr;//对指针初始化
    }
    
}

void HashMap::Insert(const std::string &key, const ElementType &element)
{
    Node*node=new Node(key,element);
    //计算哈希值
    int index =Hash(key);
    node->next=array[index];
    array[index]=node;
    
}

HashMap::~HashMap()
{
    for(int i=0;i<size;i++)
    {
        Node*TP=array[i];
       while(TP!=nullptr)
       {
        Node*temp=TP->next;
        delete TP;
        TP=temp;
       }

    }
    delete []array;
}

void HashMap::show()
{
    for(int i=0;i<size;i++)
    {
        Node*TP=array[i];
        while(TP!=nullptr)
        {
            std::cout<<"hash值"<<Hash(TP->key)<<" "
            <<"key:"<<TP->key<<" "
            <<"value:"<<TP->value<<" "<<std::endl;
            TP=TP->next;
        }
    }
}

ElementType HashMap::operator[](const std::string &key)
{   
    ElementType*data=Get(key);
    if (data)
    {
        return *data;
    }
    else
    {
        Insert(key,"");
        return*Get(key);
    }
    
}

ElementType* HashMap::Get(const std::string &key)
{
    Node*node=array[Hash(key)];
    while(node!=nullptr)
    {
        if (node->key==key)
        {
            return &node->value;
        }
        node=node->next;
    }
    return nullptr;
}

void HashMap::Remove(const std::string &key)
{
    Node*node=array[Hash(key)];
    if(node==nullptr)
        return;
    if(node->key==key)
    {
        array[Hash(key)]=node->next;
            return;
    }
    while(node!=nullptr)
    {

        if(node->next->key==key)
        {
            Node*freeNode=node->next;
            node->next=freeNode->next;
            delete freeNode;
            return;
        }
    }
}

int HashMap::Hash(const std::string &key)
{     int hash=0;
//素数
    for (int i=0;i<key.size();i++)
    {
        hash=(hash*31+key[i])%size;
    }
    return hash;
}